package com.gemme.gemme.home;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.gemme.gemme.R;
import com.gemme.gemme.SearchActivity;
import com.gemme.gemme.bravh.CustomLoadMoreView;
import com.gemme.gemme.bravh.DataServer;
import com.gemme.gemme.bravh.Status;
import com.gemme.gemme.fragment.BaseLazyFragment;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.util.Tips;
import com.gemme.gemme.view.DefineLoadMoreView;
import com.gemme.gemme.view.StaggeredDividerItemDecoration;
import com.yanzhenjie.recyclerview.OnItemClickListener;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;


/**
 * Created by sp on 2019/7/18.
 * 首页
 */
public class HomeNewFragment extends BaseLazyFragment  {

    View inflate;
    Context mContext;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        inflate = inflater.inflate(R.layout.fragment_home_new, container, false);

        mContext = HomeNewFragment.this.getContext();


        return inflate;
    }


    private SwipeRefreshLayout mRefreshLayout;
    private SwipeRecyclerView mRecyclerView;
    private List<String> mDataList;
    StaggeredDividerItemDecoration staggeredDividerItemDecoration;
    private void initView(View inflate) {
        mRefreshLayout = inflate.findViewById(R.id.refresh_layout);


        mRecyclerView = inflate.findViewById(R.id.recycler_view);
//        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        View iv_search = inflate.findViewById(R.id.iv_search);
        View brand = inflate.findViewById(R.id.brand);
        StaggeredGridLayoutManager layoutManager = new
                StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        if(staggeredDividerItemDecoration == null){
            staggeredDividerItemDecoration = new StaggeredDividerItemDecoration
                    (mContext, (int) getResources().getDimension(R.dimen.dp_11));
            mRecyclerView.addItemDecoration(staggeredDividerItemDecoration);
        }



//        mRecyclerView.addItemDecoration(new DefaultItemDecoration(ContextCompat.getColor(this, R.color.divider_color)));

//        mRecyclerView.setOnItemClickListener(mItemClickListener);

        // 自定义的核心就是DefineLoadMoreView类。
        DefineLoadMoreView loadMoreView = new DefineLoadMoreView(mContext);
        mRecyclerView.addFooterView(loadMoreView); // 添加为Footer。
        mRecyclerView.setLoadMoreView(loadMoreView); // 设置LoadMoreView更新监听。
        mRefreshLayout.setOnRefreshListener(mRefreshListener); // 刷新监听。
        mRecyclerView.setLoadMoreListener(mLoadMoreListener); // 加载更多的监听。


        // 请求服务器加载数据。
//        loadData();

        iv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), SearchActivity.class));
            }
        });
        brand.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), BrandActivity.class));
            }
        });


    }

    public static class HomeNewAdapter extends RecyclerView.Adapter<HomeNewAdapter.ViewHolder>{
        private List<HomeProductBean.DataBean.RecordsBean> mDataList;

        public HomeNewAdapter(List<HomeProductBean.DataBean.RecordsBean> records){
            mDataList = records;
        }
        public void setData(List<HomeProductBean.DataBean.RecordsBean> records) {
            mDataList = records;
            notifyDataSetChanged();
        }
        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(parent.getContext()).
                    inflate(R.layout.home_new_item, null);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            inflate.setLayoutParams(layoutParams);
            return new HomeNewAdapter.ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            try {
                HomeProductBean.DataBean.RecordsBean recordsBean = mDataList.get(position);

                holder.name.setText(recordsBean.getProductName());
                holder.price.setText("¥"+recordsBean.getProductPrice() + "");
                Glide.with(holder.picture.getContext()).load(recordsBean.getAbbreviationPic()).into(holder.picture);
            }catch (Exception e){

            }
        }

        @Override
        public int getItemCount() {
            return mDataList.size();
        }



        public class ViewHolder extends RecyclerView.ViewHolder {
            TextView name;
            TextView price;
            ImageView picture;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                name = itemView.findViewById(R.id.name);
                price = itemView.findViewById(R.id.price);
                picture = itemView.findViewById(R.id.picture);
            }
        }
    }

    protected List<String> createDataList(int start) {
        List<String> strings = new ArrayList<>();
        for (int i = start; i < start + 20; i++) {
            strings.add("第" + i + "个Item");
        }
        return strings;
    }
    /**
     * 第一次加载数据。
     */
/*
    private void loadData() {
        mDataList = createDataList(0);
        mAdapter.notifyDataSetChanged(mDataList);

        mRefreshLayout.setRefreshing(false);

        // 第一次加载数据：一定要掉用这个方法。
        // 第一个参数：表示此次数据是否为空，假如你请求到的list为空(== null || list.size == 0)，那么这里就要true。
        // 第二个参数：表示是否还有更多数据，根据服务器返回给你的page等信息判断是否还有更多，这样可以提供性能，如果不能判断则传true。
        mRecyclerView.loadMoreFinish(false, true);
    }
*/
    /**
     * 加载更多。
     */
    private SwipeRecyclerView.LoadMoreListener mLoadMoreListener = new SwipeRecyclerView.LoadMoreListener() {
        @Override
        public void onLoadMore() {
            mRecyclerView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    /*List<String> strings = createDataList(mAdapter.getItemCount());
                    mDataList.addAll(strings);
                    // notifyItemRangeInserted()或者notifyDataSetChanged().
                    mAdapter.notifyItemRangeInserted(mDataList.size() - strings.size(), strings.size());

                    // 数据完更多数据，一定要掉用这个方法。
                    // 第一个参数：表示此次数据是否为空。
                    // 第二个参数：表示是否还有更多数据。
                    mRecyclerView.loadMoreFinish(false, true);

                    // 如果加载失败调用下面的方法，传入errorCode和errorMessage。
                    // errorCode随便传，你自定义LoadMoreView时可以根据errorCode判断错误类型。
                    // errorMessage是会显示到loadMoreView上的，用户可以看到。
                    // mRecyclerView.loadMoreError(0, "请求网络失败");*/
                }
            }, 1000);
        }
    };

    /**
     * 刷新。
     */
    private SwipeRefreshLayout.OnRefreshListener mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
/*
            mRecyclerView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    loadData();
                    initData();
                }
            }, 1000); // 延时模拟请求服务器。
*/
        }
    };

    /**
     * Item点击监听。
     */
    private OnItemClickListener mItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(View itemView, int position) {
            Toast.makeText(mContext, "第" + position + "个", Toast.LENGTH_SHORT).show();
        }
    };






    @Override
    public void onLazyLoad() {

        //yc
        initView(inflate);
        initData();
//        getData();
    }
    HomeNewAdapter homeNewAdapter;
    private void initData() {
        SharedPreferences MSP = getContext().getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);
        String access_token = MSP.getString(Constant.ACCESS_TOKEN, "").trim();

        if(TextUtils.isEmpty(access_token)){
            Toast.makeText(mContext, "用户信息过期", Toast.LENGTH_SHORT).show();
            return;
        }
        String url = DataManager.BaseUrl_weicheng + "mall/shopproductinfo/page?current=1&size=10";
        HashMap<String, String> headHashMap = new HashMap<>();
//        headHashMap.put(DataManager.AuthorizationKey,"Bearer 0af0e15c-0f2c-4b75-90f2-dc2c1236524d");
        headHashMap.put(DataManager.AuthorizationKey,"Bearer " + access_token);
        DataManager.toServer2(mContext, url, DataManager.GET_TYPE, "", headHashMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try {
                    HomeProductBean homeProductBean = JSON.parseObject(response, HomeProductBean.class);
                    List<HomeProductBean.DataBean.RecordsBean> records = homeProductBean.getData().getRecords();
                    if(homeNewAdapter == null){
                        homeNewAdapter = new HomeNewAdapter(records);
                        mRecyclerView.setAdapter(homeNewAdapter);
                    }else{
                        homeNewAdapter.setData(records);
                    }
                    mRefreshLayout.setRefreshing(false);

                    // 第一次加载数据：一定要掉用这个方法。
                    // 第一个参数：表示此次数据是否为空，假如你请求到的list为空(== null || list.size == 0)，那么这里就要true。
                    // 第二个参数：表示是否还有更多数据，根据服务器返回给你的page等信息判断是否还有更多，这样可以提供性能，如果不能判断则传true。
                    mRecyclerView.loadMoreFinish(false, true);
                }catch (Exception e){

                }
            }
        });
    }


}
